package com.hh.fudan.project_management;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;

import com.hh.fudan.project_management.basic.TextUtil;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;

public class SettingsActivity extends Activity implements OnClickListener {
	private int startHour;
	private int startMinute;
	private int endHour;
	private int endMinute;
	private float latitude;
	private float longitude;

	private Button bok;
	private Spinner spinCities;
	private Spinner spinDiscountPercent;
	private Spinner spinDistances;
	private Spinner spinMembers;
	private EditText title;
	private EditText price;
	private Button bcurrentLocation;
	private TextView myLocation;

	private SharedPreferences prefs;
	private SharedPreferences.Editor editor;
	private OnSharedPreferenceChangeListener listener;

	private Resources res;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.prefsettings);

		prefs = getSharedPreferences("usersettings", 0);
		editor = prefs.edit();
		res = getResources();
		try {
			initialize();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		bcurrentLocation = (Button) findViewById(R.id.setCurrentLocation);
		bcurrentLocation.setOnClickListener(this);

	}

	public void initialize() throws IOException {
		bok = (Button) findViewById(R.id.setCurrentLocation);
		spinCities = (Spinner) findViewById(R.id.cityName);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.city_entry, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		String curCity = prefs.getString("cityName", "");
		String[] cities = res.getStringArray(R.array.city_entry);
		spinCities.setSelection(TextUtil.getStringIndex(curCity, cities));
		spinCities.setAdapter(adapter);
		spinCities.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int arg2, long arg3) {
				Spinner spinner = (Spinner) parent;
				String cityName = spinner.getSelectedItem().toString();
				editor.putString("cityName", cityName);
				editor.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});

		spinDiscountPercent = (Spinner) findViewById(R.id.discountPercent);
		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
				this, R.array.discount_array,
				android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinDiscountPercent.setAdapter(adapter2);
		String curDiscount = prefs.getString("discountPercent", "");
		String[] discounts = res.getStringArray(R.array.discount_array);
		spinDiscountPercent.setSelection(TextUtil.getStringIndex(
				convertDiscountToText(curDiscount), discounts));
		spinDiscountPercent
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View arg1, int arg2, long arg3) {
						Spinner spinner = (Spinner) parent;
						String discountPercent = spinner.getSelectedItem()
								.toString();
						discountPercent = discountConvert(discountPercent);
						editor.putString("discountPercent", discountPercent);
						editor.commit();
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}

				});

		spinDistances = (Spinner) findViewById(R.id.distance);
		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
				this, R.array.distance_entries,
				android.R.layout.simple_spinner_item);
		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinDistances.setAdapter(adapter3);
		int curDistance = prefs.getInt("distance", 0);
		String[] distances = res.getStringArray(R.array.distance_entries);
		spinDistances.setSelection(TextUtil.getStringIndex(
				convertDistanceToText(curDistance), distances));
		spinDistances.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int arg2, long arg3) {
				Spinner spinner = (Spinner) parent;
				String distances = spinner.getSelectedItem().toString();
				int distance = distanceConvert(distances);
				editor.putInt("distance", distance);
				editor.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});

		spinMembers = (Spinner) findViewById(R.id.members);
		ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
				this, R.array.people_array,
				android.R.layout.simple_spinner_item);
		spinMembers.setAdapter(adapter4);
		adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		String curMember = prefs.getString("members", "");
		String[] members = res.getStringArray(R.array.people_array);
		System.out.println("current member:" + curMember);
		spinMembers.setSelection(TextUtil.getStringIndex(
				convertMemberToText(curMember), members));

		spinMembers.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int arg2, long arg3) {
				Spinner spinner = (Spinner) parent;
				String members = spinner.getSelectedItem().toString();
				members = membersConvert(members);
				editor.putString("members", members);
				editor.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});

		title = (EditText) findViewById(R.id.title);
		title.setText(prefs.getString("title", "").replaceAll(",", " "));
		// editor.putString("title", "电影 价值");

		title.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				EditText input = (EditText) v;
				String title = input.getText().toString();
				editor.putString("title", TextUtil.splitKeywords(title));
				editor.commit();
				return false;
			}

		});

		price = (EditText) findViewById(R.id.price);
		price.setText(prefs.getString("price", ""));
		price.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				EditText input = (EditText) v;
				String price = input.getText().toString();
				editor.putString("price", price);
				editor.commit();

				return false;
			}

		});

		TimePicker startTime = (TimePicker) this.findViewById(R.id.startTime);
		startTime.setCurrentHour(prefs.getInt("startHour", 0));
		startTime.setCurrentMinute(prefs.getInt("startMinute", 0));
		startTime.setIs24HourView(true);
		startTime
				.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
					@Override
					public void onTimeChanged(TimePicker arg0, int hour,
							int minute) {
						startHour = hour;
						startMinute = minute;
						editor.putInt("startHour", startHour);
						editor.putInt("startMinute", startMinute);
						editor.commit();
						Log.d("time", hour + ":" + minute);
					}
				});

		TimePicker endTime = (TimePicker) this.findViewById(R.id.endTime);
		endTime.setIs24HourView(true);
		endTime.setCurrentHour(prefs.getInt("endHour", 0));
		endTime.setCurrentMinute(prefs.getInt("endMinute", 0));
		endTime.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
			@Override
			public void onTimeChanged(TimePicker arg0, int hour, int minute) {
				endHour = hour;
				endMinute = minute;
				Log.d("time", hour + ":" + minute);
				editor.putInt("endHour", endHour);
				editor.putInt("endMinute", endMinute);
				editor.commit();
			}
		});

		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				10000, 0, new LocationListener() {
					public void onLocationChanged(Location location) {
					}

					public void onProviderDisabled(String provider) {
					}

					public void onProviderEnabled(String provider) {
					}

					public void onStatusChanged(String provider, int status,
							Bundle extras) {
					}
				});
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 10000, 0,
				new LocationListener() {
					public void onLocationChanged(Location location) {
					}

					public void onProviderDisabled(String provider) {
					}

					public void onProviderEnabled(String provider) {
					}

					public void onStatusChanged(String provider, int status,
							Bundle extras) {
					}
				});
		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location == null)
			location = locationManager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (location != null) {
			latitude = (float) location.getLatitude();// 经度
			longitude = (float) location.getLongitude();// 纬度
		}
		

		TextView currentLocation = (TextView) findViewById(R.id.currentLocation);
		DecimalFormat formatter = new DecimalFormat("#.000");
		currentLocation.setText(formatter.format(latitude) + "(N), "
				+ formatter.format(longitude) + "(E)");

		float prefLatitude = (float) prefs.getFloat("latitude", 0);
		float prefLongitude = (float) prefs.getFloat("longitude", 0);
		myLocation = (TextView) findViewById(R.id.mylocation);
		myLocation.setText(formatter.format(prefLatitude) + "(N), "
				+ formatter.format(prefLongitude) + "(E)");

		registerPreferenceListener();
	}

	private void registerPreferenceListener() {
		listener = new OnSharedPreferenceChangeListener() {

			@Override
			public void onSharedPreferenceChanged(SharedPreferences pref,
					String key) {
				if (key.equals("cityName")) {
					String curCity = pref.getString(key, "");
					String[] cities = res.getStringArray(R.array.city_entry);
					spinCities.setSelection(TextUtil.getStringIndex(curCity,
							cities));
				} else if (key.equals("price")) {
					String curPrice = pref.getString(key, "");
					price.setText(curPrice);
				} else if (key.equals("discountPercent")) {
					String curDiscount = pref.getString(key, "");
					String[] discounts = res
							.getStringArray(R.array.discount_array);
					spinDiscountPercent.setSelection(TextUtil.getStringIndex(
							convertDiscountToText(curDiscount), discounts));
				} else if (key.equals("members")) {
					String curMember = pref.getString(key, "");
					String[] members = res.getStringArray(R.array.people_array);
					spinMembers.setSelection(TextUtil.getStringIndex(
							convertMemberToText(curMember), members));
				} else if (key.equals("title")) {
					String curTitle = pref.getString(key, "");
					title.setText(curTitle.replaceAll(",", " "));
				}
			}
		};
		prefs.registerOnSharedPreferenceChangeListener(listener);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		prefs.unregisterOnSharedPreferenceChangeListener(listener);
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == bok.getId()) {
			SharedPreferences prefs = getSharedPreferences("usersettings", 0);
			SharedPreferences.Editor editor = prefs.edit();
			String price = ((EditText) findViewById(R.id.price)).getText()
					.toString();
			String discountPercent = ((Spinner) findViewById(R.id.discountPercent))
					.getSelectedItem().toString();
			discountPercent = discountConvert(discountPercent);

			editor.putString("price", price);
			editor.putInt("distance", 1000);
			editor.putFloat("latitude", latitude);
			editor.putFloat("longitude", longitude);
			editor.commit();
		}

		else if (view.getId() == bcurrentLocation.getId()) {

			editor.putFloat("latitude", latitude);
			editor.putFloat("longitude", longitude);
			Log.d("location", "current location" + latitude + ", " + longitude);
			myLocation.setText(latitude + ", " + longitude);

		}

	}

	public String discountConvert(String s) {
		if (s.equals("小于9折"))
			return "9";
		else if (s.equals("小于8折"))
			return "8";
		else if (s.equals("小于7折"))
			return "7";
		else if (s.equals("小于6折"))
			return "6";
		else if (s.equals("小于5折"))
			return "5";
		else if (s.equals("小于4折"))
			return "4";
		else if (s.equals("小于3折"))
			return "3";
		else if (s.equals("全价"))
			return "10";
		else
			return "10";
	}

	private String convertDiscountToText(String distance) {
		if (distance.equals("10"))
			return "全价";
		else if (distance.equals("9"))
			return "小于9折";
		else if (distance.equals("8"))
			return "小于8折";
		else if (distance.equals("7"))
			return "小于7折";
		else if (distance.equals("6"))
			return "小于6折";
		else if (distance.equals("5"))
			return "小于5折";
		else if (distance.equals("4"))
			return "小于4折";
		else if (distance.equals("3"))
			return "小于3折";
		else
			return "全价";
	}

	public String membersConvert(String s) {
		if (s.equals("大于10人"))
			return "10";
		else if (s.equals("大于50人"))
			return "50";
		else if (s.equals("大于100人"))
			return "100";
		else if (s.equals("大于200人"))
			return "200";
		else if (s.equals("大于500人"))
			return "500";
		else if (s.equals("大于1000人"))
			return "1000";

		return "1000";
	}

	public String convertMemberToText(String member) {
		if (member.equals("10"))
			return "大于10人";
		else if (member.equals("50"))
			return "大于50人";
		else if (member.equals("100"))
			return "大于100人";
		else if (member.equals("200"))
			return "大于200人";
		else if (member.equals("500"))
			return "大于500人";
		else if (member.equals("1000"))
			return "大于1000人";
		else
			return "大于10人";

	}

	public int distanceConvert(String s) {
		if (s.equals("500米以内"))
			return 500;
		else if (s.equals("1公里以内"))
			return 1000;
		else if (s.equals("2公里以内"))
			return 2000;
		else if (s.equals("3公里以内"))
			return 3000;
		else if (s.equals("5公里以内"))
			return 5000;
		else if (s.equals("10公里以内"))
			return 10000;

		return 10000;
	}

	public String convertDistanceToText(int d) {
		if (d == 500)
			return "500米以内";
		else if (d == 1000)
			return "1公里以内";
		else if (d == 2000)
			return "2公里以内";
		else if (d == 3000)
			return "3公里以内";
		else if (d == 5000)
			return "5公里以内";
		else if (d == 10000)
			return "10公里以内";

		return "10公里以内";
	}
}
